package com.xasz.controller;

import com.xasz.service.ex.NotLoginException;
import com.xasz.service.ex.*;
import com.xasz.util.JsonResult;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpSession;

/**
 * 控制层基类
 * 处理: 异常、session信息
 */
public class BaseController {
    public static final int OK=200;

    /**
     * Service异常拦截器
     */
    @ExceptionHandler(ServiceException.class)
    public JsonResult<Void> handleException(Throwable e){
        JsonResult<Void> result=new JsonResult<>(e);
        if (e instanceof RepeatException ) {
            result.setState(4000);
        } else if (e instanceof CreatException) {
            result.setState(4001);
        } else if (e instanceof DeleteException) {
            result.setState(4002);
        } else if (e instanceof NotNxistException) {
            result.setState(4003);
        } else if (e instanceof UpdateException) {
            result.setState(4004);
        } else if (e instanceof NotLoginException) {
            result.setState(5000);
        }else if (e instanceof UsernameRepeatException) {
            result.setState(5001);
        } else if (e instanceof PasswordException) {
            result.setState(5002);
        } else if (e instanceof ScoreException) {
            result.setState(6000);
        } else if (e instanceof TimeException) {
            result.setState(6001);
        }
        return result;
    }

//全局异常捕获------------------------------调试时暂时关闭

//    @ExceptionHandler(Exception.class)
//    public JsonResult<Void> handle2Exception(Throwable e){
//        JsonResult<Void> result=new JsonResult<>(e);
////        if (e instanceof NullPointerException ) {
////            result.setState(3000);
////            result.setMessage("未查询到信息");
////        }
//        return result;
//    }
    /**
     * 获取session的id
     */
    protected final Integer getUidFromSession(HttpSession session){
        return Integer.valueOf(session.getAttribute("uid").toString());
    }

    /**
     * 获取session的username
     */
    protected final String getUsernameFromSession(HttpSession session){
        return session.getAttribute("username").toString();
    }


}
